<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="三餐" prop="mealType">
        <el-select v-model="queryParams.mealType" placeholder="请选择" clearable>
          <el-option
            v-for="item in dict.type.food_meals_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
          </el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="禁忌项" prop="symptomType">
            <el-select :style="{ width: '200px' }" v-model="queryParams.symptomType" placeholder="请选择" clearable>
                <el-option
                    v-for="item in dict.type.food_meals_symptom"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                </el-option>
            </el-select>                     
        </el-form-item>      
        <el-form-item label="类型" prop="code">
            <!-- <el-input :style="{ width: '200px' }" v-model="form.tagType" :min-height="192"/> -->
            <el-select :style="{ width: '200px' }" v-model="queryParams.tagType" placeholder="请选择" clearable>
                <el-option
                    v-for="item in dict.type.food_meals_tag"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                </el-option>
            </el-select>                    
        </el-form-item>  



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 添加或修改《中国食物成分》食物样品描述对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食谱名称" prop="name">
          <el-input :style="{ width: '200px' }" v-model="form.name" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="食谱编码" prop="code">
          <el-input :style="{ width: '200px' }" v-model="form.code" placeholder="请输入食谱编码" />
        </el-form-item>
        <!-- <el-form-item label="食谱类型" prop="mealType">
            <el-select :style="{ width: '200px' }" v-model="form.mealType" placeholder="请选择">
                <el-option
                    v-for="item in dict.type.food_meals_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    clearable>
                </el-option>
            </el-select>       
        </el-form-item> -->
        <el-form-item label="食谱图片" prop="cover">
            <el-upload
              ref="upload"
              list-type="picture-card"
              :on-remove="handleRemove"
              :http-request="handleUploadFile"
              :file-list="form.cover"
              action="#"
              >
              <i class="el-icon-plus"></i>
            </el-upload>        
        </el-form-item>
        
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="foodopen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item>
            <el-button v-if="form.fctMealsSampleVOs && form.fctMealsSampleVOs.length === 0" class="btn"  @click="addMeal" type="primary">添加食物</el-button>
            <div v-for="(item,index) in form.fctMealsSampleVOs" :key="index">
                <el-form-item>
                  <el-select
                      :style="{ width: '200px',margin: '10px 0 10px 0' }"
                      v-model="form.fctMealsSampleVOs[index].sampleId"
                      filterable
                      remote
                      reserve-keyword
                      placeholder=""
                      :remote-method="(query) => remoteMethodFront(query, item)"
                      @focus="remoteMethodFront(undefined, item)"
                      clearable
                      >
                      <el-option
                        v-for="item in sampleList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      <span style="float: left">{{ item.name }}</span>
                      <img style="float: right; width: 30px; height: 30px;" v-if="item.cover.length>0" :src="'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + item.cover[0].url" />
                      </el-option>
                  </el-select>   
                  <el-input :style="{ width: '100px', margin: '10px' }" class="cen-input" v-model="form.fctMealsSampleVOs[index].content" placeholder="重量" />
                  <el-select :style="{width: '200px', margin: '10px 0 0px 0' }" v-model="form.fctMealsSampleVOs[index].unitsId" placeholder="请选择">
                      <el-option
                      v-for="item in unitsList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                      </el-option>
                  </el-select> 
                  <el-button class="btn"  @click="delMeal(index)" :style="{margin: '0 0 0 10px' }" type="danger">删除</el-button>
                  <el-button class="btn" v-if="index === form.fctMealsSampleVOs.length - 1 " @click="addMeal" type="primary">添加</el-button>
                </el-form-item>

                

            </div> 
        </el-form-item>          
        
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="tocancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="150" />
      <el-table-column label="食谱名称" align="center" prop="name" width="200"/>
      <el-table-column label="食谱编码" align="center" prop="code" />
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <div class="top-img">
          <img :src="'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/'+scope.row.cover[0].url" v-if="scope.row.cover[0]" class="avatar"/> 
          </div>
        </template>
      </el-table-column>
      <el-table-column label="抗炎指数" align="center" prop="antiInflammatory" />

      <el-table-column label="类型" align="center" prop="tagType" >
            <template slot-scope="scope" v-if="scope.row.tagType"> 
              {{(dict.type.food_meals_tag.find(obj => obj.value === scope.row.tagType).label)}}
            </template>      
      </el-table-column>
      <el-table-column label="禁忌" align="center" prop="symptomType">
            <template slot-scope="scope" v-if="scope.row.symptomType">
              {{(dict.type.food_meals_symptom.find(obj => obj.value === scope.row.symptomType).label)}}
            </template>          
      </el-table-column>
      <el-table-column label="三餐" align="center" key="mealType" width="100">
            <template slot-scope="scope" v-if="scope.row.mealType">
              {{(dict.type.food_meals_type.find(obj => obj.value === scope.row.mealType).label)}}
            </template>
      </el-table-column>


      <el-table-column label="创建时间" align="center" width="155" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddFood(scope.row)"
            v-hasPermi="['system:info:edit']"
          >添加食物</el-button>         
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/food/meals";
import { listSample} from "@/api/food/foodmanage";
import { listUnits } from "@/api/food/units";

import {
	put,
	getUrl,
} from '@/components/Upload/uploadOss.js'
export default {
  name: "Info",
  dicts: ['food_meals_type', 'food_meals_tag', 'food_meals_symptom'],
  data() {
    return {
      unitsList: [],  
      sampleList: [],
      foodopen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        openId: null,
        name: null,
        nickname: null,
        headImg: null,
        phone: null,
        mealType: null,
        symptomType: null,
        tagType: null,
      },
      // 表单参数
      form: {
        mealType: '4'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "食谱名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "食谱编码不能为空", trigger: "blur" }
        ],
        mealType: [
          { required: true, message: "食谱类型不能为空", trigger: "change" }
        ],  
        cover: [
          { required: true, message: "食谱图片不能为空", trigger: "blur" }
        ],                         
      }
    };
  },
  created() {
    this.getList();
  },
  mounted(){
    this.loading = true;
    listUnits(this.queryParams).then(response => {
        this.unitsList = response.rows;
    });

    listSample(
        {
            pageNum: 1,
            pageSize: 2000,
          }
    ).then(response => {
        this.sampleList = response.rows;
        this.loading = false;
        console.log('static222',this.sampleList);
    });   

    // console.log('static2222',this.unitsList);
  },  
  methods: {
    addMeal(){
        this.form.fctMealsSampleVOs.push({
            "mealsId": this.form.id,
            "sampleId": "",
            "content": "",
            "unitsId": "1"
        })
    },   
   delMeal(index){
        this.form.fctMealsSampleVOs.splice(index,1);
    },   
    remoteMethodFront(query, item) {
        if (query !== '') {
          listSample({
            name: query,
            pageNum: 1,
            pageSize: 2000,
            compositionId: item.compositionId || item.compositionDetlId
          }).then(response => {
              this.sampleList = response.rows;
            });

        } else {
          this.sampleList = [];
        }
      },     
    handleRemove(file) {
      this.form.cover = this.form.cover.filter((item)=>(item.url) != file.url)
      console.log(this.form.cover);
    },

		handleUploadFile(option) {
				this.loading = true
				//获取上传后的url
				const _name = this.getDate() + '/' + option.file.uid + '.' + option.file.name.split('.')[1]
				put(_name, option.file).then((res) => {
					if (res) {
						getUrl(res.name).then((rel) => {
              console.log('static',rel);
							this.form.cover.push({
                url:'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + _name
              })
						})
					} else {
					}
            this.loading = false
				})
		},     
    
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    tocancel(){
      this.foodopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        openId: null,
        name: null,
        nickname: null,
        headImg: null,
        phone: null,
        cover: [],
        delFlag: null,
        status: null,
        updateBy: null,
        createBy: null,
        updateTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAddFood(row) {
      console.log('static',row);
      getInfo(row.id).then(response => {
        this.form = response.data;
        this.foodopen = true;
        this.title = row.name;
      });


    },      
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.mealType = 4
      this.open = true;
      this.title = "添加食谱信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.$router.push('/nutrition/mealsdetail?id='+ row.id)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cover = this.form.cover.map(item => (
                  {
                    ...item,
                    url: this.toUrl(item.url)
                  }
            )
          )          
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              if(response.code === 200){
                this.$modal.msgSuccess("添加食物成功");
                this.foodopen = false;
                this.getList();
              }

            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除食谱名称为"' + row.name + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.top-img{
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
}

.cen-input{
  width: 100upx !important;
}


.avatar {
  width: 58px;
  height: 58px;
  display: block;
}
</style> 